﻿using Blm.Utils.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using VisionSurface.Service.Wx;

namespace VisionSurface.Web.Controllers.Wx
{
    /// <summary>
    /// 微信消息推送
    /// </summary>
    [Route("api/miniapp/wx/[controller]")]
    [ApiVersion("1.0")]
    [ApiExplorerSettings(GroupName = "微信消息推送")]
    public class WebchatController : ApiBaseController
    {
        private readonly ILogger<WebchatController> logger;
        private readonly WxApiService wxApiService;

        public WebchatController(ILogger<WebchatController> logger, WxApiService wxApiService)
        {
            this.logger = logger;
            this.wxApiService = wxApiService;
        }

        /// <summary>
        /// 确认此次 GET 请求来自微信服务器
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public IActionResult Get(string signature, string timestamp, string nonce, string echostr)
        {
            // 验证URL  
            if (wxApiService.CheckSignature(signature, timestamp, nonce))
            {
                logger.LogInformation($"确认此次 GET 请求来自微信服务器");
                return Content(echostr);
            }

            return BadRequest();
        }

        /// <summary>
        /// 接收微信推送的消息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public IActionResult Post([FromBody] JObject json)
        {
            if (json == null)
            {
                return BadRequest("请求数据不能为空");
            }

            logger.LogInformation($"接收到微信推送消息：{json.ToJsonStr()}");

            return Content("success");
        }
    }
}
